package com.zmn.oms.business.impl.comment;

import com.google.common.collect.Lists;
import com.zmn.comment.common.dio.cmt.CommentDIO;
import com.zmn.comment.common.dio.cmt.label.CommentLabelDIO;
import com.zmn.comment.common.dro.cmt.label.config.LabelConfigDRO;
import com.zmn.comment.common.enums.CommentObjectTypeEnum;
import com.zmn.comment.dubbo.interfaces.cmt.CmtCommentModifyRemoteService;
import com.zmn.comment.dubbo.interfaces.cmt.label.config.CmtLabelConfigListRemoteService;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.oms.business.interfaces.comment.OrderCommentBService;
import com.zmn.oms.common.annotation.ZsNormalOrderWorkLog;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.dto.MapDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.vo.KVDict;
import com.zmn.oms.model.dto.comment.OrderCommentDTO;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.comment.OrderCommentService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 类描述：评价
 *
 * @author lujia
 * @date 2019/01/23 20:32
 */
@Slf4j
@Service
public class OrderCommentBServiceImpl implements OrderCommentBService {

    @Autowired
    private OrderCommentService orderCommentService;
    @Autowired
    private OrderWorkService orderWorkService;


    @Reference(version = com.zmn.comment.dubbo.interfaces.utils.DubboConsts.INTERFACE_VERSION, check = false)
    private CmtCommentModifyRemoteService cmtCommentModifyRemoteService;
    @Reference(version = com.zmn.comment.dubbo.interfaces.utils.DubboConsts.INTERFACE_VERSION, check = false)
    private CmtLabelConfigListRemoteService cmtLabelConfigListRemoteService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_COMMENT, beforeProceed = false)
    public void saveComment(OrderCommentDTO orderCommentDTO) throws OmsBaseException {
        // 保存到订单系统
        saveCommentData(orderCommentDTO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_COMMENT_APPEND)
    public void saveThirdComment(OrderCommentDTO orderCommentDTO) throws OmsBaseException {
        saveCommentData(orderCommentDTO);
    }

    /**
     * 保存评价扩展数据
     * @param orderCommentDTO
     */
    private void saveCommentData(OrderCommentDTO orderCommentDTO) throws OmsBaseException {
        CommentDIO commentDIO = new CommentDIO();
        commentDIO.setCommentObjectId(orderCommentDTO.getWorkId());
        commentDIO.setCommentObjectType(CommentObjectTypeEnum.COMMENT_OBJECT_TYPE_ORDER.getCode());
        commentDIO.setOperatorId(orderCommentDTO.getOperatorId());
        commentDIO.setOperatorType(orderCommentDTO.getOperatorType());
        commentDIO.setOperatorName(orderCommentDTO.getOperator());
        commentDIO.setCommentType(orderCommentDTO.getType());
        commentDIO.setScore(orderCommentDTO.getScore());
        if (StringUtil.isNotBlank(orderCommentDTO.getPicUrls())) {
            commentDIO.setPicUrlsList(Lists.newArrayList(orderCommentDTO.getPicUrls()));
        }
        commentDIO.setContent(orderCommentDTO.getContent());
        if (CollectionUtil.isNotNullOrEmpty(orderCommentDTO.getCodeMapList())) {
            List<CommentLabelDIO> commentLabelList = new ArrayList<>();
            for (MapDTO mapDTO : orderCommentDTO.getCodeMapList()) {
                if (Objects.equals(mapDTO.getStatus(), GlobalConsts.YES)) {
                    CommentLabelDIO commentLabelDIO = new CommentLabelDIO();
                    commentLabelDIO.setLabelId(mapDTO.getMapId());
                    commentLabelDIO.setLabelName(mapDTO.getMapName());
                    commentLabelList.add(commentLabelDIO);
                }
            }
            commentDIO.setCommentLabelList(commentLabelList);
        }
        log.info("cmtCommentModifyRemoteService.addComment params={}", commentDIO);
        ResponseDTO responseDTO = null;
        try {
            responseDTO = cmtCommentModifyRemoteService.addComment(commentDIO);
        } catch (Exception e) {
            log.error("cmtCommentModifyRemoteService.addComment error={}", e.getMessage());
            throw e;
        }
        log.info("cmtCommentModifyRemoteService.addComment result={}", responseDTO);
        if (!responseDTO.isSuccess()) {
            throw new OmsBaseException(responseDTO.getStatus(), responseDTO.getMessage());
        }
    }

    @Override
    public List<KVDict<Integer>> listLabelConfigByBizTypeAndStar(Integer bizType, Integer businessLine, Integer score) {
        log.info("cmtLabelConfigListRemoteService.listLabelConfigByBizTypeAndStar bizType={},businessLine={},score={}", bizType, businessLine, score);
        ResponseDTO<List<LabelConfigDRO>> listResponseDTO = null;
        List<KVDict<Integer>> typeList = Lists.newArrayList();
        try {
            listResponseDTO = cmtLabelConfigListRemoteService.listLabelConfigByBizTypeAndStar(bizType, Lists.newArrayList(businessLine), score);
        } catch (Exception e) {
            log.error("cmtLabelConfigListRemoteService.listLabelConfigByBizTypeAndStar error={}", e.getMessage());
            return typeList;
        }

        log.info("cmtLabelConfigListRemoteService.listLabelConfigByBizTypeAndStar result={}", listResponseDTO);
        if (!listResponseDTO.isSuccess() || CollectionUtil.isNullOrEmpty(listResponseDTO.getData())) {
            return typeList;
        }
        listResponseDTO.getData().forEach(labelConfigDRO -> typeList.add(KVDict.<Integer>builder().value(labelConfigDRO.getLabelId()).text(labelConfigDRO.getName()).build()));
        return typeList;
    }

    /**
     * 校验是否需要评价
     * @param orderCommentDTO
     * @throws OmsBaseException
     */
    private OrderWork validateSupportComment(OrderCommentDTO orderCommentDTO) throws OmsBaseException {
        Long orderId = orderCommentDTO.getOrderId();

        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);
        if (orderWork == null) {
            throw new OmsBaseException("订单不存在");
        }

        Integer status = orderWork.getStatus();
        if (status < OrderStatusConsts.WORK_STATUS_COMPLETE) {
            throw new OmsBaseException("订单未完成");
        }

        return orderWork;
    }
}
